<template>
    <view>
      <view class="app_sip">
          <view class="tabs">
                <view class="uni-tab-item-title uni-tab-item-title-active">SIP设置</view>
                <view class="uni-tab-item-title" style="float:right;" >
                	<u-button :class="isShowBtn == true ? 'sip_btn_disabled':'sip_btn_active'" :disabled="isShowBtn" :custom-style="btnStyle" @click.top="handleOpenAppSipRefresh()" ><uni-icons type="refresh" color="#fff" size="22"></uni-icons> 刷新</u-button>
                </view>
          </view>
        <web-view ref="webview" allow :webview-styles="{width: '0', height: '0',top:'80',bottom:'80',border:'#ff0000 1px solid',overflow:'hidden'}" :src="targetUrl" @message="handleMessage" :fullscreen="false" ></web-view>
      </view>
      
      <u-modal v-model="showTip" :show-cancel-button="true" :show-title="false" style="position: absolute;z-index:100000000000000000000000000000000;" content="刷新时,本页数据将重置" @confirm="handleRefreshAppSip()" @cancel="handleCloseAppSipRefresh()"></u-modal>
	</view>
</template>


<script>
import infoSelf from "@/pages/index/infoself.vue";

import {
	mapGetters,mapState
} from "vuex";

let that;

export default {
    data() {
        return {			
			targetUrl:'',
            btnStyle: {
            	border: 'none',
            	borderRadius: '50rpx',
            	color: '#fff',
            	padding:'20rpx 25rpx',
            	margin:'0rpx'
            },
            
            isShowBtn:false,
            showTip:false,
            
            webViewHeight:'80%',
            webViewWidth:'100%',
            webViewTop:'80',
            webViewBottom:'80'
        }
    },
	props:['currentpage'],
	computed: {
		...mapGetters(["userInfo","isSip","sipPhone","isShowWebSip","websipCallStatus","callStatus","callingData","currentCallType"]),
        ...mapState({
            isSip:state=>state.task.isSip,
            sipPhone:state=>state.task.sipPhone,
            isShowWebSip:state=>state.task.isShowWebSip,
			callingData:state=>state.task.callingData,
			callStatus:state=>state.task.callStatus,
            websipCallStatus:state=>state.task.websipCallStatus,
			currentCallType:state=>state.task.currentCallType
        })
	},
	mounted() {
        that = this;
        
		this.initData();
	},
	components:{infoSelf},
    methods: {
		initData(){
			const currentWebview = this.$parent.$scope.$getAppWebview();
			console.log("aaaaaaaaaaa",currentWebview);
            
            this.targetUrl = this.userInfo.main_ip + "/appsip?seat=" + this.userInfo.seat;
			// this.targetUrl = "http://192.168.3.5:8089/appsip?seat=11004";
            
            console.log("targeturl",this.targetUrl);
            
            that.$console.info("websip url: ", this.targetUrl);
            that.$console.info("websip userinfo: ", this.userInfo);
            
			setTimeout(()=>{
				let wv = currentWebview.children()[0];
				wv.hide();
                
                wv.setStyle({
                    height:'0',
                    width:'0'
                });
                
                //默认设置成开启免提
                that.toggleSpeakerphone({value:false});
			},200)
		},
        
        //打开appsip刷新窗口
        handleOpenAppSipRefresh(){
            const currentWebview = this.$parent.$scope.$getAppWebview();
            console.log("aaaaaaaaaaa",currentWebview);
            
            setTimeout(()=>{
            	let wv = currentWebview.children()[0];
            	wv.hide();
                
                wv.setStyle({
                    height:'0',
                    width:'0'
                });
                
                this.showTip = true;
            },200)
        },
        
        //关闭appsip刷新客串
        handleCloseAppSipRefresh(){
            this.showTip = false;
            
            const currentWebview = this.$parent.$scope.$getAppWebview();
            console.log("aaaaaaaaaaa",currentWebview);
            
            setTimeout(()=>{
            	let wv = currentWebview.children()[0];
            	wv.show();
                
                wv.setStyle({
                    height:that.webViewHeight,
                    width:that.webViewWidth,
                    top:that.webViewTop,
                    bottom:that.webViewBottom
                })
                
            },200)
        },
        
        //刷新重新加载APPsip页
        handleRefreshAppSip(){
            this.isShowBtn = true;
            
            this.showTip = false;
            
            const currentWebview = this.$parent.$scope.$getAppWebview();
            console.log("aaaaaaaaaaa",currentWebview);
            
            setTimeout(()=>{
            	let wv = currentWebview.children()[0];
            	wv.show();
                
                wv.setStyle({
                    height:that.webViewHeight,
                    width:that.webViewWidth,
                    top:that.webViewTop,
                    bottom:that.webViewBottom
                });
                
                wv.reload();
            },200)
            
            setTimeout(()=>{
                this.isShowBtn = false;
            },3000);
        },
		
		//挂断通话
		handleEndCall(){
		    that.$callModule.endCall(res => {
		        console.log("endCall",res);
		      
		        that.$store.dispatch("setCallStatus",0);
				that.$store.dispatch("setCallingData",{id:'',phone:'',type:''});
				
				that.$store.dispatch("setCurrentCallType","");

		        //that.$store.dispatch("setWebsipCallStatus","hangup");
		    });
		},
        
        //接收web-view发送的数据
        handleMessage(e) {
            let data = e.detail.data[0];
            
            console.log("eeeee",e,data);
            
            that.$console.info("websip handleMessage e: ", e);
            that.$console.info("websip handleMessage data: ",data);
            
            if(data != null && data != undefined){
                if(data.code == 'sipin'){
                    //SIP注册成功
                    that.$store.dispatch("setIsSip",1);
                }else if(data.code == "sipout"){
                    //SIP注销
                    that.$store.dispatch("setIsSip",0);
				}else if(data.code == 'mute'){
					//开启静音
					that.toggleMute();
				}else if(data.code == 'speaker'){
					//开启，关闭免提
					that.toggleSpeakerphone(data);
				}else if(data.code == "callout"){
                    //WEBSIP推送数据，通话失败，通话成功 状态
                    infoSelf.methods.handleChangeNumStatus({'num':data.num,'status':data.status});
					if(data.status != 2 || data.status != '2'){
						that.handleEndCall();
					}else{
                        that.$store.dispatch("setCallingData",{id:'0',phone:data.num,type:'index',state:'callout'});
                    }
                }else if(data.code == "callstart"){
					//WEBSIP开始呼叫，振铃
					that.$store.dispatch("setCallStatus",1);
					that.$store.dispatch("setCallingData",{id:'0',phone:data.num,type:'index',state:'callstart'});
					that.$store.dispatch("setCurrentCallType",'sip');
				}else if(data.code == "callend"){
					//WEBSIP通话结束  
					infoSelf.methods.handleChangeNumStatus({'num':data.num,'status':data.status});
					that.handleEndCall();
				}
            }
        },
        
        // 切换免提
        toggleSpeakerphonesss(data){
			console.log("toggleSpeakerphone",uni.getSystemInfoSync());
        	if(uni.getSystemInfoSync().platform === 'android'){
        		//const AudioManager = plus.android.importClass('android.media.AudioManager');
        		const Context = plus.android.importClass('android.content.Context');
        		
        		// 获取 AudioManager 实例
        		const audioService = plus.android.runtimeMainActivity().getSystemService(Context.AUDIO_SERVICE);
        		// const isSpeakerOn = plus.android.invoke(audioService, 'isSpeakerphoneOn');
        		
				// let isSpeakerOn = data.message == "开启免提" ? true : false; 
				let isSpeakerOn = data.value;
        		console.log("isSpeakerOn",isSpeakerOn);
        		
        		// 切换状态
        		plus.android.invoke(audioService, 'setSpeakerphoneOn', isSpeakerOn);
				  
        	}
        },
		
		toggleSpeakerphone(data){
			let sys_info = uni.getSystemInfoSync();
			
			console.log("sys_info",sys_info);
			
			if (sys_info.platform === 'android') {
			    const AudioManager = plus.android.importClass('android.media.AudioManager');
			    const Context = plus.android.importClass('android.content.Context');
				
				let romVersion = sys_info.romVersion.split(".");
			    
			    // 获取 AudioManager 实例
			    const audioService = plus.android.runtimeMainActivity().getSystemService(Context.AUDIO_SERVICE);
			    // const currentVolume = plus.android.invoke(audioService, 'getStreamVolume', AudioManager.STREAM_MUSIC);
				
				const maxVolume = plus.android.invoke(audioService, 'getStreamMaxVolume', AudioManager.STREAM_MUSIC);
				
				let isSpeakerOn = data.value;
				let currentVolume = Math.trunc(maxVolume * 0.5);
				
			    
				if((sys_info.romName == 'HarmonyOS' && romVersion[0]*1 >= 4) ){
					// 切换静音（设置音量为0或恢复）
					console.log("speaker data",data,maxVolume);
					if (data.value == false) {
						console.log("speaker 100",data);
						plus.android.invoke(audioService, 'setStreamVolume', AudioManager.STREAM_MUSIC, currentVolume, 0);
					} else {
						console.log("speaker 0",data);
						const maxVolume = plus.android.invoke(audioService, 'getStreamMaxVolume', AudioManager.STREAM_MUSIC);
						plus.android.invoke(audioService, 'setStreamVolume', AudioManager.STREAM_MUSIC, maxVolume, 0); //AudioManager.FLAG_SHOW_UI
					}
				}else{
					// 切换状态
					plus.android.invoke(audioService, 'setSpeakerphoneOn', isSpeakerOn);
				}
			}
		},
        
        // 切换静音
        toggleMute(){
            if (uni.getSystemInfoSync().platform === 'android') {
                const AudioManager = plus.android.importClass('android.media.AudioManager');
                const Context = plus.android.importClass('android.content.Context');
                
                // 获取 AudioManager 实例
                const audioService = plus.android.runtimeMainActivity().getSystemService(Context.AUDIO_SERVICE);
                const currentVolume = plus.android.invoke(audioService, 'getStreamVolume', AudioManager.STREAM_MUSIC);
                
                // 切换静音（设置音量为0或恢复）
                if (currentVolume > 0) {
        			plus.android.invoke(audioService, 'setStreamVolume', AudioManager.STREAM_MUSIC, 0, AudioManager.FLAG_SHOW_UI);
                } else {
        			const maxVolume = plus.android.invoke(audioService, 'getStreamMaxVolume', AudioManager.STREAM_MUSIC);
        			plus.android.invoke(audioService, 'setStreamVolume', AudioManager.STREAM_MUSIC, maxVolume, AudioManager.FLAG_SHOW_UI);
                }
            }
        },
		
        //发送数据到web-view嵌套页
        handleSendMessage(code,value) {
			
			console.log("eeeee",code,value);
			let _funName = "msgFromUniapp";
			
			const currentWebview = that.$parent.$scope.$getAppWebview();
			console.log("aaaaaaaaaaa",currentWebview);
			setTimeout(()=>{
				let wv = currentWebview.children()[0];
				let params = {"code":code,"value":value};
				// wv.evalJS(`${_funName}(${JSON.stringify(e.detail.data)})`);
                
                wv.evalJS(`${_funName}(${JSON.stringify(params)})`);
                console.log("wv.evaljs");
                
                //清空数据
                // uni.setStorageSync("sipPhone",{});
                that.$store.dispatch("setSipPhone","");
			},200)
        }
    },
	watch: {
	    sipPhone(newVal, oldVal) {
			console.log("websip ",newVal,oldVal,this.sipPhone);
            // 监听文本框值的改变
            if (newVal != "" && newVal != null && newVal != undefined) {
                if(this.isShowWebSip == '0'){
                    const currentWebview = this.$parent.$scope.$getAppWebview();
                    console.log("aaaaaaaaaaa",currentWebview);
                    
                    that.$console.info("websip currentWebview 1:",currentWebview);
                    
                    currentWebview.setStyle({'position':'absolute','z-index':100});
                    setTimeout(()=>{
                        let wv = currentWebview.children()[0];
                        wv.show();
                        
                        wv.setStyle({
                            height:that.webViewHeight,
                            width:that.webViewWidth,
                            top:that.webViewTop,
                            bottom:that.webViewBottom
                        });
                    },200);
                    
                }else{
                    const currentWebview = this.$parent.$scope.$getAppWebview();
                    console.log("aaaaaaaaaaa 2",currentWebview);
                    that.$console.info("websip currentWebview 2:",currentWebview);
                    setTimeout(()=>{
                        let wv = currentWebview.children()[0];
                        wv.hide();
                        
                        wv.setStyle({
                            height:'0',
                            width:'0'
                        });
                    },200)
                }
                
                //检测坐席是否过期
                const expire_time = this.userInfo.expire_time;
                let is_expire = false;
                if(expire_time != "" && expire_time != "" && expire_time != undefined){
                    let expire_time_formate = new Date(expire_time).getTime();
                    let current_time = new Date().getTime();
                    
                    console.log("current_time",expire_time_formate,current_time);
                    that.$console.info("websip currentpage: ",expire_time_formate + "," + current_time);
                    
                    if(expire_time*1 < current_time){
                        is_expire = true;
                        
                        //过期，清空 token, 跳转到登录页                            
                        that.$console.info("websip currentpage: 过期，清空 token, 跳转到登录页");
                        
                        uni.setStorageSync("token","");
                        uni.showToast({
                            title: '账号已到期，请先充值',
                            icon: 'none',
                            duration: 3000,
                            complete: function() {
                                uni.reLaunch({
                                    url: '/pages/index/login'
                                });
                            }
                        });
                    }
                }
                
                if(!is_expire){
                
                    //判断是否有号码
                    let sip_phone_data = this.sipPhone;
                    //if(sip_phone_data != "" && sip_phone_data != null && sip_phone_data != undefined ){
                        that.handleSendMessage('phone',{'phone':sip_phone_data});
                    //}
                }
            }
	    },
        
        currentpage(newVal, oldVal) {
        	console.log("websip",newVal,oldVal,this.userInfo,uni.getStorageSync("sipPhone"));
            // 监听文本框值的改变
            // if (newVal !== oldVal) {
                if(newVal == 'websip'){
                    const currentWebview = this.$parent.$scope.$getAppWebview();
                    console.log("aaaaaaaaaaa",currentWebview);
                    
                    that.$console.info("websip currentWebview 1:",currentWebview);
                    
                    currentWebview.setStyle({'position':'absolute','z-index':100});
                    setTimeout(()=>{
                        let wv = currentWebview.children()[0];
                        wv.show();
                        
                        wv.setStyle({
                            height:that.webViewHeight,
                            width:that.webViewWidth,
                            top:that.webViewTop,
                            bottom:that.webViewBottom
                        });
                    },200);
                    
                }else{
                    const currentWebview = this.$parent.$scope.$getAppWebview();
                    console.log("aaaaaaaaaaa 2",currentWebview);
                    that.$console.info("websip currentWebview 2:",currentWebview);
                    setTimeout(()=>{
                        let wv = currentWebview.children()[0];
                        wv.hide();
                        
                        wv.setStyle({
                            height:'0',
                            width:'0'
                        });
                    },200)
                }
            // }
        },
        
        websipCallStatus(newVal,oldVal){
            console.log("websipCallStatus",newVal,oldVal,this.userInfo,uni.getStorageSync("websipCallStatus"));
            if(newVal == "hangup"){
                //websip 挂断
                that.handleSendMessage('hangup',"");
                
                that.$store.dispatch("setWebsipCallStatus","");
            }
        },
        
        // currentpage(newVal, oldVal) {
        // 	console.log("websip",newVal,oldVal,this.userInfo,uni.getStorageSync("sipPhone"));
        //     // 监听文本框值的改变
        //     if (newVal !== oldVal) {
        //         if(newVal == 'websip'){
        //             const currentWebview = this.$parent.$scope.$getAppWebview();
        //             console.log("aaaaaaaaaaa",currentWebview);
                    
        //             that.$console.info("websip currentWebview 1:",currentWebview);
                    
        //             currentWebview.setStyle({'position':'absolute','z-index':100});
        //             setTimeout(()=>{
        //                 let wv = currentWebview.children()[0];
        //                 wv.show();
                        
        //                 wv.setStyle({
        //                     height:that.webViewHeight,
        //                     width:that.webViewWidth
        //                 });
        //             },200);
                    
                    
        //             //检测坐席是否过期
        //             const expire_time = this.userInfo.expire_time;
        //             let is_expire = false;
        //             if(expire_time != "" && expire_time != "" && expire_time != undefined){
        //                 let expire_time_formate = new Date(expire_time).getTime();
        //                 let current_time = new Date().getTime();
                        
        //                 console.log("current_time",expire_time_formate,current_time);
        //                 that.$console.info("websip currentpage: ",expire_time_formate + "," + current_time);
                        
        //                 if(expire_time*1 < current_time){
        //                     is_expire = true;
                            
        //                     //过期，清空 token, 跳转到登录页                            
        //                     that.$console.info("websip currentpage: 过期，清空 token, 跳转到登录页");
                            
        //                     uni.setStorageSync("token","");
        //                     uni.showToast({
        //                         title: '账号已到期，请先充值',
        //                         icon: 'none',
        //                         duration: 3000,
        //                         complete: function() {
        //                             uni.reLaunch({
        //                                 url: '/pages/index/login'
        //                             });
        //                         }
        //                     });
        //                 }
        //             }
                    
        //             if(!is_expire){
                    
        //                 //判断是否有号码
        //                 let sip_phone_data = uni.getStorageSync("sipPhone");
        //                 if(sip_phone_data.phone != "" && sip_phone_data.phone != null && sip_phone_data.phone != undefined ){
        //                     that.handleSendMessage('phone',sip_phone_data);
        //                 }
        //             }
        //         }else{
        //             const currentWebview = this.$parent.$scope.$getAppWebview();
        //             console.log("aaaaaaaaaaa 2",currentWebview);
        //             that.$console.info("websip currentWebview 2:",currentWebview);
        //             setTimeout(()=>{
        //                 let wv = currentWebview.children()[0];
        //                 wv.hide();
                        
        //                 wv.setStyle({
        //                     height:'0',
        //                     width:'0'
        //                 });
        //             },200)
        //         }
        //     }
        // }
        
	}
};
</script>

<style lang="scss" scoped>
	.app_sip{
		width:100%;
		height:80%;
        position: absolute;
		overflow:hidden;
        top:10%;
        // background-color: #333;
	}
	
	.tabs {
	    background-color: #ffffff;
	    
		width:100%;
		height:190rpx;
		top:0rpx;
		// margin-left:20rpx;
	    
		position: fixed;
		z-index: 1000;
		
	}
    
    .sip_btn_active{
        float:right;
        margin-right:13rpx;
        height:60rpx;
        background: linear-gradient(90deg, #5498ff 0%, #34b1ff 100%);
    }
    
    .sip_btn_disabled{
        float:right;
        margin-right:13rpx;
        height:60rpx;
        color:#333 !important;
        border:#fff 1px solid !important;
        border-radius: 50rpx !important;
        background: linear-gradient(90deg, #e5e5e5 0%, #d3d3d3 100%);
    }
	
	.uni-tab-item-title {
	    color: #555;
	    font-size: 36rpx;
	    line-height: 60rpx;
	    flex-wrap: nowrap;
		margin-left:20rpx;
	    margin-right:20rpx;
		margin-top:80rpx;
		
		float:left;
	    /* #ifndef APP-PLUS */
	    white-space: nowrap;
	    /* #endif */
	}
	
	.uni-tab-item-title-active {
		font-size:36rpx;
		font-weight: bold;
		border-bottom:3px #0b2eb0 solid;
	}
	
</style>

